package com.bw.kotlinim.contract.login

import com.bw.kotlinim.adapter.EMCallbackAdapter
import com.bw.kotlinim.extention.isValidPassword
import com.bw.kotlinim.extention.isValidUserName
import com.hyphenate.chat.EMClient

class LoginPresenter(private val view: LoginContract.View) : LoginContract.Presenter {
    override fun login(userName: String, password: String) {
        if (userName.isValidUserName()) {
            //1.验证用户名合法
            if (password.isValidPassword()) {
                //2.验证密码合法
                //3.开始登录
                view.onStartLogin()//触发进度条
                loginEaseMob(userName, password)//登录到环信

            } else view.onPasswordError()
        } else view.onUserNameError()


    }

    //相当于M层
    private fun loginEaseMob(userName: String, password: String) {
        EMClient.getInstance().login(userName, password, object : EMCallbackAdapter() {
            override fun onSuccess() {
                //去参考环信文档
                EMClient.getInstance().groupManager().loadAllGroups()
                EMClient.getInstance().chatManager().loadAllConversations()
                runOnUIThread { view.onLoggedInSuccess() }
            }

            override fun onError(code: Int, error: String?) {
                runOnUIThread {
                    view.onLoggedInFailed(error.toString())
                }
            }
        })
    }

}